import GameModel from '../../../model/GameModel.js'
import router from '@ohos.router';
import prompt from '@ohos.prompt';
import featureAbility from '@ohos.ability.featureAbility';
import RemoteDeviceModel from '../../../model/RemoteDeviceModel.js';
import { ServiceModel } from "../../../model/ServiceModel.js"
import rpc from '@ohos.rpc';
import commonEvent from '@ohos.commonEvent'
import deviceManager from '@ohos.distributedHardware.deviceManager';

let DEVICE_LIST_LOCALHOST;
const TAG = "[SETTING]"
const START_GAME_CODE = 101; // 业务码 开始游戏
let mDeviceManager = null;

export default {
    data: {
        playGameAnimation: null,
        selectGameModel: 0,
        GameModel: new GameModel(),
        curNickName: '',
        deviceList: [],
        remoteDeviceModel: new RemoteDeviceModel(),
        isCentralDevice: true,
        serviceModel: new ServiceModel(),
        mSubscriber: null,
        mDeviceId: '',
        isFight : false,// 是否为对战模式,
        fightId: ''// 对战ID
    },

    onInit() {
        DEVICE_LIST_LOCALHOST = {
            name: this.$t('strings.localhost'),
            id: 'localhost'
        };
        this.deviceList = [DEVICE_LIST_LOCALHOST];
        this.selectGameModel = this.GameModel.MODEL_EASY;
        let params = router.getParams();
        if (typeof (params) != 'undefined') {
            this.curNickName = params.nick_name;
            this.isCentralDevice = params.is_central_device;
            if (!this.isCentralDevice) {
                this.isFight = true;// 如果为附设备则当前处于对战模式
                // 启动服务
                this.onConnectService();
            }
        }
    },

    onConnectService() {
        this.getDeviceList();
    },

    onDisconnectService() {
        this.serviceModel.disconnectService(); // 断开服务
    },

    onShow() {
        console.info(`${TAG} onShow`);
        // 清除堆栈中的其他页面
        router.clear();
        // 开始游戏按钮的动画
        var options = {
            duration: 750,
            easing: 'linear',
            iterations: -1,
            direction: 'alternate'
        };
        var frames = [
            {
                width: 286,
                height: 154,
            },
            {
                width: 250,
                height: 127,
            }
        ];
        if (this.playGameAnimation === null) {
            this.playGameAnimation = this.$element('startGameDiv').animate(frames, options); //获取动画对象
        }
        this.playGameAnimation.play();
    },

    onChange(data) {
        this.selectGameModel = data.index;
        if (this.isCentralDevice) {
            if (this.selectGameModel === this.GameModel.MODEL_FIGHT) {
                this.isFight = true;
            } else {
                this.isFight = false;
            }
        }
    },

    onHide() {
        console.info(`${TAG} onHide`);
        this.onStopAnimation();
    },

    /**
     * 开始游戏
     */
    onStartGame() {
        if (this.isCentralDevice) {
            if (this.selectGameModel === this.GameModel.MODEL_FIGHT) {
                // 创建公共事件--监听开始游戏
                this.createSubscriber();
                // 对战模式则开启连接局域网内的其他设备
                this.continueAbility();
            } else {
                // 进入游戏
                this.gotoGamePage(this.selectGameModel);
            }
        } else {
            // 通知另外一台设备已开始游戏
            this.sendStartGameRequest();
        }
    },

    sendStartGameRequest() {
        console.info(`${TAG} sendStartGameRequest`);
        let remote = this.serviceModel.getRemoteObject();
        console.info(`${TAG} remote ${remote}`);
        if (remote === null) {
            this.showToast("服务连接中...");
            this.onConnectService();
            return;
        }
        let option = new rpc.MessageOption(); // 消息对象，本次请求的同异步模式，默认同步调用
        // MessageParcel 提供读写基础类型及数组、IPC对象、接口描述符和自定义序列化对象的方法。
        let data = rpc.MessageParcel.create(); // 保存待发送数据的 MessageParcel对象
        let reply = rpc.MessageParcel.create(); // 接收应答数据的MessageParcel对象
        data.writeInt(this.selectGameModel);
        this.fightId = this.guid();
        data.writeString(this.fightId);
        let self = this;
        // 发起请求，参数1：业务码
        let promise = remote.sendRequest(1, data, reply, option);
        promise.then((result) => {
            console.info(`${TAG} sendRequest result：${result}`);
            if (result.errCode === 0) {
                // 获取发送给服务处理的结果
                console.info(`${TAG} sendRequest go to Game Page`);
                self.gotoGamePage(self.selectGameModel);
            } else {
                console.info(`${TAG} sendRequest fail errorCode：${result.errCode}`);
            }
        }).catch((e) => {
            console.info(`${TAG} sendRequest exception:${JSON.stringify(e)}`);
        }).finally(() => {
            console.info(`${TAG} sendRequest end`);
            data.reclaim(); // 释放不再使用的MessageParcel对象
            reply.reclaim();
        })
    },

    gotoGamePage(gameModel) {
        this.onStopAnimation();
        var params = {
            game_model: gameModel,
            nick_name: this.curNickName,
            is_fight: this.isFight,
            fight_id: this.fightId
        };
        router.push({
            url: "pages/game/game",
            params: params
        });
    },

    onPreviousModel() {
        this.$element('gameModel').showPrevious();
    },

    onNextModel() {
        this.$element('gameModel').showNext();
    },

    onShowTop() {
        var params = {
            nick_name: this.curNickName
        };
        router.push({
            url: "pages/top/top",
            params: params
        });
    },

    onStopAnimation() {
        if (this.playGameAnimation) {
            this.playGameAnimation.cancel();
            console.info(`${TAG} Animation cancel`);
        }
    },

    onDestroy() {
        console.info(`${TAG} onDestroy`);
        this.onStopAnimation();
        this.remoteDeviceModel.unregisterDeviceListCallback();
        this.onDisconnectService();
        this.unsubscribe();
        console.info('onDestroy end');
    },

    cancelDialog() {
        this.remoteDeviceModel.unregisterDeviceListCallback();
    },

    onDismissDialogClicked() {
        this.dismissDialog();
    },

    dismissDialog() {
        this.$element('continueAbilityDialog').close();
        this.remoteDeviceModel.unregisterDeviceListCallback();
    },

    continueAbility() {
        console.info('onContinueAbilityClick begin');
        const self = this;
        this.remoteDeviceModel.registerDeviceListCallback(() => {
            console.info('registerDeviceListCallback, callback entered');
            const list = [];
            list[0] = DEVICE_LIST_LOCALHOST;
            let deviceList;
            if (self.remoteDeviceModel.discoverList.length > 0) {
                deviceList = self.remoteDeviceModel.discoverList;
            } else {
                deviceList = self.remoteDeviceModel.deviceList;
            }
            console.info('on remote device updated, count=' + deviceList.length);
            for (let i = 0; i < deviceList.length; i++) {
                console.info('device ' + i + '/' + deviceList.length + ' deviceId='
                + deviceList[i].deviceId + ' deviceName=' + deviceList[i].deviceName + ' deviceType='
                + deviceList[i].deviceType);
                list[i + 1] = {
                    name: deviceList[i].deviceName,
                    id: deviceList[i].deviceId
                };
            }
            self.deviceList = list;
        });
        this.$element('continueAbilityDialog').show();
        console.info('onContinueAbilityClick end');
    },

    onRadioChange(inputValue, e) {
        console.info('onRadioChange ' + inputValue + ', ' + e.value);
        if (inputValue === e.value) {
            if (e.value === 'localhost') {
                this.$element('continueAbilityDialog').close();
                return;
            }
            if (this.remoteDeviceModel.discoverList.length > 0) {
                console.info('continue to unauthed device');
                let name = null;
                for (let i = 0; i < this.remoteDeviceModel.discoverList.length; i++) {
                    if (this.remoteDeviceModel.discoverList[i].deviceId === e.value) {
                        name = this.remoteDeviceModel.discoverList[i].deviceName;
                        break;
                    }
                }
                if (name === null) {
                    console.error('onRadioChange failed, can not get name from discoverList');
                    return;
                }
                console.info('onRadioChange name=' + name);

                const self = this;
                this.remoteDeviceModel.authDevice(e.value, () => {
                    console.info('auth and online finished');
                    for (let i = 0; i < self.remoteDeviceModel.deviceList.length; i++) {
                        if (self.remoteDeviceModel.deviceList[i].deviceName === name) {
                            this.startAbilityContinuation(self.remoteDeviceModel.deviceList[i].deviceId, self.remoteDeviceModel.deviceList[i].deviceName);
                        }
                    }
                });
            } else {
                console.info('continue to authed device');
                for (let i = 0; i < this.remoteDeviceModel.deviceList.length; i++) {
                    if (this.remoteDeviceModel.deviceList[i].deviceId === e.value) {
                        this.startAbilityContinuation(this.remoteDeviceModel.deviceList[i].deviceId, this.remoteDeviceModel.deviceList[i].deviceName);
                    }
                }
            }
        }
    },

    startAbilityContinuation(deviceId, deviceName) {
        this.$element('continueAbilityDialog').close();
        console.info('featureAbility.startAbility deviceId=' + deviceId
        + ' deviceName=' + deviceName);
        const wantValue = {
            bundleName: 'com.nlas.focusgame',
            abilityName: 'com.example.entry.MainAbility',
            deviceId: deviceId
        };
        featureAbility.startAbility({
            want: wantValue
        }).then((data) => {
            console.info('featureAbility.startAbility finished, ' + JSON.stringify(data));
        });
        console.info('featureAbility.startAbility want=' + JSON.stringify(wantValue));
        console.info('featureAbility.startAbility end');
    },

    showToast(msg) {
        prompt.showToast({
            message: msg,
            duration: 2000
        });
    },

    //----注册公共事件----
    createSubscriber() {
        if (this.mSubscriber != null) {
            return;
        }
        // Subscriber information
        var subscribeInfo = {
            events: ["startGame"] // 开始游戏
        }
        // Create subscriber callback
        commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
            if (err.code) {
                console.error(`${TAG} [CommonEvent]CreateSubscriberCallBack err = ${JSON.stringify(err)}`)
                this.showToast('绑定失败');
            } else {
                console.log(`${TAG} [CommonEvent]CreateSubscriber`)
                this.mSubscriber = subscriber
                this.subscribe();
            }
        })
    },

    subscribe() {
        // Subscribe
        let self = this;
        if (this.mSubscriber != null) {
            commonEvent.subscribe(this.mSubscriber, (err, data) => {
                if (err.code) {
                    console.error(`${TAG} [CommonEvent]SubscribeCallBack err= = ${JSON.stringify(err)}`)
                } else {
                    console.info(`${TAG} [CommonEvent]SubscribeCallBack data= = ${JSON.stringify(data)}`)
                    let code = data.code;
                    switch (code) {
                        case (START_GAME_CODE):
                        {
                            // 启动游戏
                            self.fightId = data.parameters.fightId;
                            self.gotoGamePage(data.parameters.gameModel);
                            break;
                        }
                        default:
                            {
                                break;
                            }
                    }
                }
            })
            console.log(`${TAG} [CommonEvent] Subscribe succeed`);
            this.showToast('绑定成功');
        } else {
            console.error(`${TAG} [CommonEvent] Need create subscriber`);
            this.showToast('请先绑定事件');
        }
    },

    unsubscribe() {
        // Unsubscribe CommonEvent
        if (this.mSubscriber != null) {
            commonEvent.unsubscribe(this.mSubscriber, (err) => {
                if (err.code) {
                    console.error(`${TAG}[CommonEvent]UnsubscribeCallBack err= = ${JSON.stringify(err)}`);
                    this.showToast('事件解绑失败');
                } else {
                    console.info(`${TAG} [CommonEvent]Unsubscribe success`)
                    this.showToast('事件解绑成功');
                    this.mSubscriber = null
                }
            })
        }
    },



    // 注册设备列表回调
    getDeviceList() {
        console.info(`${TAG} getDeviceList`);
        if (mDeviceManager === null) {
            // 获取设备管理对象
            let self = this;
            deviceManager.createDeviceManager('com.nlas.focusgame',
                (error, value) => {
                    if (error) {
                        console.info(`${TAG} createDeviceManager failed. ${error}`);
                        return;
                    }
                    mDeviceManager = value;// 设备管理器对象实例
                    self.getAndConnectDevice();
                })
        } else {
            this.getAndConnectDevice();
        }
    },

    getAndConnectDevice(){
        var list = mDeviceManager.getTrustedDeviceListSync();
        console.info(`${TAG} deviceList ${JSON.stringify(list)}`);
        if (list != null) {
            this.mDeviceId = list[0].deviceId;
            console.info(`${TAG} mDeviceId ${this.mDeviceId}`);
            this.serviceModel.connectService(this.mDeviceId); // 连接服务
        }
    },

    guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    },

    gotoIntroduction() {
        router.push({
            url: "pages/introduction/introduction",
        });
    },

    gotoRule() {
        router.push({
            url: "pages/rule/rule",
        });
    }
}
